package com.halobop.demo.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.halobop.demo.admin.dto.UserLoginDto;
import com.halobop.demo.admin.dto.UserQueryDto;
import com.halobop.demo.admin.dto.UserRegisterDto;
import com.halobop.demo.admin.service.IUserService;
import com.halobop.demo.mbg.mapper.UserMapper;
import com.halobop.demo.mbg.model.User;
import com.halobop.demo.mbg.model.UserExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public int register(UserRegisterDto dto) {
        User user = new User();
        user.setPhone(dto.getPhone());
        user.setPassword(dto.getPassword());
        user.setTmCreate(System.currentTimeMillis());
        user.setTmUpdate(System.currentTimeMillis());
        return userMapper.insertSelective(user);
    }


    @Override
    public Long login(UserLoginDto dto) {
        UserExample userExample = new UserExample();
        UserExample.Criteria userCriteria = userExample.createCriteria();
        userCriteria
                .andPhoneEqualTo(dto.getPhone())
                .andPasswordEqualTo(dto.getPassword());
        List<User> list = userMapper.selectByExample(userExample);
        if (list == null && list.size() <= 0){
            return null;
        }
        long userId = list.get(0).getId();
        User user = new User();
        user.setId(userId);
        user.setTmLogin(System.currentTimeMillis());
        userMapper.updateByPrimaryKeySelective(user);
        return userId;
    }

    @Override
    public List<User> pagelist(UserQueryDto dto) {
        if (dto.getPages() != null && dto.getCount() != null){
            PageHelper.startPage(dto.getPages(), dto.getCount());
        }
        UserExample userExample = new UserExample();
        UserExample.Criteria userCriteria = userExample.createCriteria();
        if (dto.getId() != null){
            userCriteria.andIdEqualTo(dto.getId());
        }
        if (dto.getPhone() != null){
            userCriteria.andPhoneLike('%' + dto.getPhone() + '%');
        }
        return userMapper.selectByExample(userExample);
    }
}
